package com.itheima.spring.bestpractive.common.interceptor;

import com.itheima.spring.bestpractive.common.exception.BizEnum;
import com.itheima.spring.bestpractive.common.exception.BizException;
import com.itheima.spring.bestpractive.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @version 1.0
 * @author: HZY
 * @date: 2025/6/20 10:23
 * @Content: token拦截器
 */
@Component
public class MyHandleInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK); // 返回200
            return true;
        }

        String token = request.getHeader("token");
        if(token == null){
            throw new BizException(BizEnum.TOKEN_MISSING);
        }
        Claims claims;
        try {
            claims = jwtUtil.parseToken(token);
        } catch (ExpiredJwtException e) {
            throw new BizException(BizEnum.TOKEN_EXPIRED); // 你自定义的枚举和异常
        } catch (JwtException e) {
            throw new BizException(BizEnum.TOKEN_INVALID);
        }
        String s = redisTemplate.opsForValue().get("token:" + claims.getSubject());
        if(!token.equals(s)){
            throw new BizException(BizEnum.TOKEN_INVALID);
        }
        return true;
    }
}
